package main;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;

public class App {
    public static void main(String[] args) {
        int b = 300;
        int a = -300;
        System.out.println("b的二进制存储形式为:"+to32binary(Integer.toBinaryString(b)));
        System.out.println("a的二进制存储形式为:"+to32binary(Integer.toBinaryString(a))+" 为b的补码形式存储");
        byte[] bytes = new byte[4];
        System.out.println("\n\n");
        bytes[0] = (byte) (a&0xff);
        bytes[1] = (byte) ((a>>8)&0xff);
        bytes[2] = (byte) ((a>>16)&0xff);
        bytes[3] = (byte) ((a>>24)&0xff);
        System.out.println("=================bytes[]转译前的值====================");
        System.out.println("bytes[0]的二进制存储形式为:"+to32binary(Integer.toBinaryString(bytes[0])));
        System.out.println("bytes[1]的二进制存储形式为:"+to32binary(Integer.toBinaryString(bytes[1])));
        System.out.println("bytes[2]的二进制存储形式为:"+to32binary(Integer.toBinaryString(bytes[2])));
        System.out.println("bytes[3]的二进制存储形式为:"+to32binary(Integer.toBinaryString(bytes[3])));
        System.out.println("=================bytes[]转译前的值====================\n\n");
        System.out.println("=================bytes[]转译后的值====================");
        System.out.println(to32binary(Integer.toBinaryString(bytes[0]&0xff)));
        System.out.println(to32binary(Integer.toBinaryString(((bytes[1]&0xff)<<8))));
        System.out.println(to32binary(Integer.toBinaryString(((bytes[2]&0xff)<<16))));
        System.out.println(to32binary(Integer.toBinaryString(((bytes[3]&0xff)<<24))));
        System.out.println("=================bytes[]转译后的值====================\n\n");
        System.out.println("=================bytes[]转int====================");
        Integer a$ = ((bytes[0]&0xff)|((bytes[1]&0xff)<<8)|((bytes[2]&0xff)<<16)|(bytes[3]&0xff)<<24);
        System.out.println("a$ = [" + a$ + "]");
        System.out.println("=================bytes[]转int====================");

    }


    private static String to32binary(String binaryString){
        Integer fill_length = 32 - binaryString.length();
        String fill_head = "0";
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<fill_length;i++){
            sb.append(fill_head);
        }
        return sb.toString()+binaryString;
    }
}
